# 
#  server.py
#  CSP2MiG
#  
#  Created by Morten A. Bentsen on 2008-10-26.
#  See LICENSE.txt for licensing details (GPLv2).

import os
import pickle
import mig.core
import time

class Migsession:
	# ===================================
	# = Reads the input on the MiG side =
	# ===================================
	def read_input(self):
		if os.environ.has_key('CSP2MIG_WORKING_FOLDER') and os.environ.has_key('CSP2MIG_INPUT'):
			if os.environ.has_key('CSP2MIG_COMPRESS') and os.environ['CSP2MIG_COMPRESS'] == 'True':
				self.compress = True
			else:
				self.compress = False
				
			self.cwd = os.getcwd()
			wf = os.environ['CSP2MIG_WORKING_FOLDER']
			# change to working directory
			os.chdir(wf)		
			input_file = os.environ['CSP2MIG_INPUT']
			if self.compress:
				retval = mig.core.unpickle_compressed(input_file)
			else:					
				f = open(input_file,'r')
				retval = pickle.load(f)
				f.close()
			self.start_time = time.time()
			return retval
		else:
			raise Exception, 'MiG env vars missing'
	
	# =================================
	# = Writes output on the MiG side =
	# ================================= 
	def write_output(self,output_data):
		end_time = time.time() - self.start_time
		if os.environ.has_key('CSP2MIG_OUTPUT'):
			output_file = os.environ['CSP2MIG_OUTPUT']
			if self.compress:
				mig.core.pickle_compressed(output_file,(output_data,end_time))
			else:					
				f = open(output_file,'w')
				pickle.dump((output_data, end_time), f)
				f.close()							

			# switch back to old working dir
			os.chdir(self.cwd)
		else:
			raise Exception, 'MiG env vars missing'
	


